package com.zb777.shuzhilingxi.service.impl;

import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.zb777.shuzhilingxi.Pojo.dto.MistakenQuestionListDTO;
import com.zb777.shuzhilingxi.Pojo.entity.MistakenQuestion;
import com.zb777.shuzhilingxi.Pojo.entity.MistakenQuestionList;
import com.zb777.shuzhilingxi.context.BaseContext;
import com.zb777.shuzhilingxi.mapper.MistakenQuestionListMapper;
import com.zb777.shuzhilingxi.result.Result;
import com.zb777.shuzhilingxi.service.IMistakenQuestionListService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import reactor.core.publisher.Flux;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author author
 * @since 2025-07-11
 */
@Service
@Slf4j
public class MistakenQuestionListServiceImpl extends ServiceImpl<MistakenQuestionListMapper, MistakenQuestionList> implements IMistakenQuestionListService {

    @Override
    public Result saveMistakenQuestionlist(MistakenQuestionListDTO mistakenQuestionListDTO) {
        Integer userId = BaseContext.getCurrentId();
        MistakenQuestionList mistakenQuestionList = new MistakenQuestionList()
        .setName(mistakenQuestionListDTO.getName())
        .setUserId(userId)
        .setCount(0)
        .setCreatedAt(LocalDateTime.now()).setIsDeleted( false);
        log.info("保存的错题列表：{}", mistakenQuestionList);
        save(mistakenQuestionList);
        return Result.success("创建成功");
    }

    @Override
    public Result<List<MistakenQuestionList>> selectMistakenQuestionlist() {
        List<MistakenQuestionList> list = lambdaQuery().eq(MistakenQuestionList::getIsDeleted, false).list();
        if (list == null||list.isEmpty()){
            return Result.success(Collections.emptyList());
        }
        return Result.success(list);
    }

    @Override
    @Transactional
    public Result deleteMistakenQuestionlist(Integer ListId) {

        try {
             Db.lambdaUpdate(MistakenQuestion.class).set(MistakenQuestion::getIsDeleted, true)
                    .eq(MistakenQuestion::getQuestionListId, ListId).update();

            lambdaUpdate().set(MistakenQuestionList::getIsDeleted, true)
                    .eq(MistakenQuestionList::getListId, ListId).update();
        } catch (Exception e) {
           e.printStackTrace();
        }
        return Result.success("删除成功");
    }

    @Override
    public Result<Flux<String>> updateMistakenQuestionlist(Integer listId, MistakenQuestionListDTO mistakenQuestionListDTO) {
    lambdaUpdate().set(MistakenQuestionList::getName, mistakenQuestionListDTO.getName())
            .eq(MistakenQuestionList::getListId, listId).update();
        return Result.success("修改成功");
    }
}
